package com.simple.shiro;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.simple.entity.SysMenu;
import com.simple.entity.SysRole;
import com.simple.entity.SysUser;
import com.simple.service.SysMenuService;
import com.simple.service.SysUserService;
import com.simple.utils.RedisUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义Realm
 */
public class MyRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(MyRealm.class);

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysMenuService sysMenuService;
    @Autowired
    com.simple.service.SysRoleService SysRoleService;
    @Autowired
    RedisUtils redisUtil;
    @Autowired
    SessionDAO sessionDAO;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if(user.getSysRole()!=null) {
            simpleAuthorizationInfo.addRole(user.getSysRole().getRoleName());//权限名称
            SysRole noteRoles =SysRoleService.findByRoleId(user.getSysRole().getId());
            String[] ids=noteRoles.getMenuId().split(",");
            List<SysMenu> menuList=sysMenuService.findByMenuIds(ids);
            Set<String> permission=new HashSet<String>();
            for (SysMenu sysMenu : menuList) {
                if(StringUtils.isNotBlank(sysMenu.getPermission())) {
                    permission.add(sysMenu.getPermission());
                }
            }
            simpleAuthorizationInfo.addStringPermissions(permission);
        }
        return simpleAuthorizationInfo;
    }

    //认证（登录）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username=(String) token.getPrincipal();
        //根据用户名查询信息
        SysUser user=sysUserService.selectUserName(username);
        if(user==null) {
            throw new UnknownAccountException("无效的用户名");
        }else {
            if(user.getStatus()==0) {
                throw new DisabledAccountException("未激活账户");
            }
        }
        //是否显示单人登录
        // 获取所有session
//        Collection<Session> sessions = sessionDAO.getActiveSessions();
//        for (org.apache.shiro.session.Session session: sessions) {
//            String loginUserSession=(String) session.getAttribute(SysConfig.USER_SESSION_KEY);
//            // 如果session里面有当前登陆的，则证明是重复登陆的，则将其剔除
//            if(loginUserSession!=null&&loginUserSession.equals(username)){
//                sessionDAO.delete(session);
//            }
//        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user, user.getPassword(),getName()) ;
        return info;
    }
}
